package com.mframe.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mframe.system.MFrameConstant;

/**
 * @author cuijr
 * sessionFilter为了把session获取到并放到线程池中	
 */
public class SessionFilter implements Filter {
	private static Logger logger = LoggerFactory.getLogger(SessionFilter.class);

	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpSession session = request.getSession();
		String uri = request.getRequestURI();
		//过滤脚本文件正常通过
		if (uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".gif")
				|| uri.endsWith(".png") || uri.endsWith(".jpg")
				|| uri.endsWith(".jpge") || uri.endsWith(".htm")
				|| uri.endsWith(".html") || uri.endsWith(".jsgz")
				|| uri.endsWith(".cssgz")) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}
		//正常路径正常通过
		if ((uri.endsWith("loginAction.action"))
				|| (uri.endsWith("loginAction!login.action"))
				|| (uri.endsWith("login.jsp"))
				|| (uri.endsWith("loginAction!loginErro.action"))
				|| (uri.endsWith("loginErro.jsp"))
				|| (uri.endsWith("loginAction!logOut.action"))) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}
		boolean isHasLogin = false;
		Object loginInfo = session
				.getAttribute(MFrameConstant.SESSION_LOGIN_NAME);
		isHasLogin = (loginInfo != null);
		// 如果没有登录 返回登录页面
		if (!isHasLogin) {
			if ((uri.endsWith("index.jsp")) || (uri.endsWith("/"))) {
				request.getRequestDispatcher("/login.jsp").forward(
						servletRequest, servletResponse);
				return;
			}
			request.getRequestDispatcher("/loginAction!loginErro.action")
					.forward(servletRequest, servletResponse);
			return;
		}

		boolean isNewSession = session.isNew();
		if (isNewSession) {
			logger.info("sessionfilter 判断 session is new ");
			SessionManager.clean();
		}
		logger.info("sessionFilter filter :{}", uri);
		SessionManager.setSession(session);
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void init(FilterConfig config) throws ServletException {
	}

}
